/**
 * Created by zhangleileiCo on 2018/10/16.
 */


var DownloadDoc = function() {
    function b(f, d, e, c) {
        $.ajax({
            url: LC.BASE_PATH + "/documents/" + f,
            type: "POST",
            dataType: "json",
            data: {
                id: d
            }
        }).done(function(g) {
            if (1 * g.success === 1) {
                var h = g.details.job.state;
                if (h === "pending" || h === "in_progress") {
                    setTimeout(function() {
                        b("get-update-tm", d, e, c)
                    }, 500)
                } else {
                    if (h === "finished_with_errors" && typeof e === "function") {
                        e(g)
                    } else {
                        if (h === "finished_successfully" && typeof c === "function") {
                            c(g)
                        }
                    }
                }
            } else {
                e(g)
            }
        })
    }
    return {
        updateTm: function(d, e, c) {
            b("update-tm", d, e, c)
        },
        startGenerate: function(c, d) {
            $.ajax({
                url: LC.BASE_PATH + "/projects/start-generate-file",
                type: "POST",
                dataType: "json",
                data: {
                    targetFileId: c
                }
            }).done(d)
        },
        generateFileStatus: function(c, d) {
            $.ajax({
                url: LC.BASE_PATH + "/projects/get-generate-file-status/" + c,
                dataType: "json"
            }).done(d)
        }
    }
}();
var FeedbackSubmit = {
    validate_form: function(c) {
        var b = $("#send-feedback");
        b.validate({
            errorElement: "div",
            rules: {
                feedback: {
                    required: true,
                    maxlength: 255
                },
                hiddenRecaptcha: {
                    required: function() {
                        return (grecaptcha.getResponse() == "")
                    }
                }
            },
            messages: {
                feedback: {
                    required: i18n("required", i18n("samples_segment")),
                    maxlength: i18n("max_length", [i18n("samples_segment"), 255])
                }
            },
            invalidHandler: function() {
                setTimeout(function() {
                    $(".bg-btn").removeClass("busy")
                }, 200)
            },
            submitHandler: function() {
                b.find("input[type=submit]").attr("disabled", "disabled");
                $.ajax({
                    url: LC.BASE_PATH + "/feedback-email",
                    type: "POST",
                    data: b.serialize(),
                    dataType: "json"
                }).done(function(d) {
                    if (d.success == 1) {
                        c(d);
                        Notification.success(i18n("success_sending_feedback"), "#desc", "", false)
                    } else {}
                })
            }
        })
    }
};
var a;
var onloadCallback = function() {
    $(".g-recaptcha").html("");
    a = grecaptcha.render($(".g-recaptcha")[0], {
        sitekey: "6Lf80gcTAAAAADQCqExYdSq-Nxe1GyI13lTWxcLj"
    })
};

function closeWindow() {
    if (LC.UE.tmId) {
        DownloadDoc.updateTm(LC.UE.targetFileId, closeEditor, closeEditor())
    } else {
        closeEditor()
    }
}
$(function() {
    LC.TITLE = i18n("editor_title");
    initEditor();
    $(".download-btn span").text(i18n("download_file_text"));
    var e = $(".download-btn");
    e.removeClass("hide");
    e.click(function() {
        var h = LC.UE.targetFileId,
            i = $(this).find(".icon");
        if (i.hasClass("ic-activity-indicator")) {
            return
        }
        loadingIcon(i, true);
        DownloadDoc.startGenerate(h, function(j) {
            if (j.success == 1) {
                g(h, i)
            } else {
                loadingIcon(i);
                Msg.error("", i18n("generic_error"))
            }
        })
    });
    if (LC.UE.docId != 0) {
        var b = $("#submit-btn"),
            d = $("#reject-btn");
        b.removeClass("hide");
        b.text(i18n("submit"));
        d.text(i18n("reject"));
        if (LC.UE.allowReject) {
            d.removeClass("hide")
        }
        b.click(function() {
            if (LC.UE.profile === "post-edit") {
                c("close")
            } else {
                c("accept")
            }
        });
        d.click(function() {
            c("reject")
        })
    }
    function c(h) {
        var k = "",
            j = "";
        switch (LC.UE.profile) {
            case "review":
                k = i18n("complete_review_" + h + "_title");
                j = i18n("complete_review_" + h + "_text");
                break;
            case "sign-off":
                k = i18n("complete_sign_off_" + h + "_title");
                j = i18n("complete_sign_off_" + h + "_text");
                break;
            case "post-edit":
                k = i18n("complete_translation_title");
                j = i18n("complete_translation_text");
                break
        }
        if (h === "reject") {
            var i = '<br /><label style="vertical-align: top"><span style="color: #e04a32">*</span>&nbsp;' + i18n("complete_reject_comment") + '&nbsp;</label><textarea id="reject_comment" rows="3" cols="50" required maxlength="1000"></textarea>';
            Msg.confirm({
                modalId: "submit_confirm",
                title: k,
                message: j + i,
                closeOnYes: true,
                iconClass: "ic-sc-warning-big",
                openCallback: function() {
                    $("#reject_comment").on("keyup paste cut input", function() {
                        var l = $(".reject_task_finish");
                        setTimeout(function() {
                            var m = $("#reject_comment");
                            if (m[0].checkValidity() && $.trim(m.val()).length >= 3) {
                                if (l.hasClass("disabled")) {
                                    l.removeClass("disabled").removeAttr("disabled")
                                }
                            } else {
                                if (!l.hasClass("disabled")) {
                                    l.addClass("disabled").attr("disabled", "disabled")
                                }
                            }
                        }, 500)
                    })
                },
                buttons: [{
                    text: i18n("btn_finish"),
                    "class": "bg-btn lc-primary reject_task_finish disabled",
                    disabled: true,
                    click: function() {
                        var l = $.trim($("#reject_comment").val());
                        $.ajax({
                            url: LC.BASE_PATH + "/projects/tasks/" + LC.UE.taskId + "/status/" + h,
                            method: "POST",
                            dataType: "json",
                            data: {
                                settings: {},
                                comment: l
                            }
                        }).done(function() {
                            try {
                                if (window.opener !== null && window.opener.LC) {
                                    window.opener.location.reload()
                                }
                                window.close()
                            } catch (m) {
                                window.close()
                            }
                        })
                    }
                }, {
                    text: i18n("btn_cancel"),
                    "class": "bg-btn",
                    click: function() {
                        $(this).dialog("close")
                    }
                }]
            })
        } else {
            Msg.confirm({
                title: k,
                message: j,
                closeOnYes: true,
                yesText: i18n("btn_finish"),
                iconClass: "ic-sc-warning-big",
                yesClass: "bg-btn lc-primary",
                cancelText: i18n("btn_cancel"),
                yesCallback: function() {
                    $.ajax({
                        url: LC.BASE_PATH + "/projects/tasks/" + LC.UE.taskId + "/status/" + h,
                        method: "POST",
                        dataType: "json",
                        data: {
                            settings: {}
                        }
                    }).done(function() {
                        try {
                            if (window.opener !== null && window.opener.LC) {
                                window.opener.location.reload()
                            }
                            window.close()
                        } catch (l) {
                            window.close()
                        }
                    })
                }
            })
        }
    }
    window.onbeforeunload = function() {
        if (LC.UE.tmId) {
            DownloadDoc.updateTm(LC.UE.targetFileId, null, function() {
                return true
            })
        }
    };

    function g(h, i) {
        DownloadDoc.generateFileStatus(h, function(k) {
            if (k.success == 1) {
                var l = k.details.job;
                if (l.state === "in_progress") {
                    setTimeout(function() {
                        g(h, i)
                    }, 500)
                } else {
                    loadingIcon(i);
                    if (l.details.nativeFileId != null && l.state === "finished_successfully") {
                        var j = l.details.nativeFileId;
                        Utils.downloadFile(j, LC.BASE_PATH + "/projects/download-file/" + j);
                        if (LC.UE.tmId) {
                            DownloadDoc.updateTm(h, function() {
                                Msg.error("", i18n("update_tm_error"))
                            })
                        }
                    } else {
                        Msg.error("", i18n("generating_error"))
                    }
                }
            } else {
                loadingIcon(i);
                Msg.error("", i18n("generic_error"))
            }
        })
    }(function f() {
        $.ajax({
            url: LC.BASE_PATH + "/projects/get-job-by-type/" + LC.UE.targetFileId + "/" + LC.UE.profile,
            dataType: "json"
        }).done(function(h) {
            if (h.success == 1) {
                setTimeout(f, 300000)
            } else {
                if (LC.UE.docId != 0) {
                    location.reload()
                }
            }
        })
    })()
});
$.ajaxSetup({
    statusCode: {
        500: function() {
            Msg.error("", i18n("subs_generic_error"), closeEditor)
        },
        401: function() {
            Msg.error("", i18n("access_denied_error"), closeEditor)
        },
        400: function() {
            Msg.error("", i18n("session_expired_error"), closeEditor)
        }
    }
});

function closeEditor() {
    try {
        if (window.opener !== null && window.opener.LC) {
            var b = window.open("", "documents");
            if (typeof b !== "undefined") {
                b.focus()
            }
        }
        window.close()
    } catch (c) {
        window.close()
    }
}
function loadingIcon(c, b) {
    if (b) {
        c.addClass("ic-activity-indicator");
        c.html("<svg><circle cx='10' cy='10' r='8'/><path d='M10,2 A8,8 0 0,1 18,10'/><path d='M18,9.8 A8,8 0 0,1 10,18'/></svg>")
    } else {
        c.removeClass("ic-activity-indicator");
        c.html("")
    }
};
